package com.cby.android.sample.model

import android.app.Application
import com.cby.android.library.base.BaseStateViewModel
import com.cby.android.sample.bean.MetaImageBean
import com.cby.android.sample.intent.MetaImageIntent
import com.cby.android.sample.repository.MetaApi
import com.cby.android.sample.repository.MetaApiImpl
import com.cby.android.sample.state.HomeState
import com.cby.android.sample.state.MetaImageState

/**
 * @description: MetaImageViewModel
 * @author: ChenBaoYang
 * @createDate: 2022/4/27 11:04 上午
 */
class MetaImageViewModel(application: Application)
    : BaseStateViewModel<MetaImageState, MetaImageIntent>(application) {

    private val api: MetaApi = MetaApiImpl()

    private var currentPage = 0

    lateinit var keyword: String

    private fun loadData() {
        fetchDataWithNoStatus{
            if(currentPage == 0) {
                showLoading()
            }
            val response = api.loadMetaImages(keyword, currentPage, 20)
            if(response.list.isEmpty() && currentPage == 0) {
                showEmpty()
            }else{
                updateState(MetaImageState(list = response.list as MutableList<MetaImageBean>,
                    page = currentPage))
                showContent()
            }
        }
    }

    override fun showError(errorMsg: String?) {
        if(currentPage > 0){
            updateState(
                MetaImageState(
                errorMsg = errorMsg
                )
            )
        }else{
            super.showError(errorMsg)
        }
    }


    override fun dispatch(intent: MetaImageIntent) {
        when(intent) {
            MetaImageIntent.LoadDataIntent -> {
                currentPage = 0
                loadData()
            }
            MetaImageIntent.LoadMoreDataIntent -> {
                currentPage++
                loadData()
            }
        }
    }
}
